//
//  evaluationViewController.m
//  随便点
//
//  Created by MWJ on 15/3/12.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "evaluationViewController.h"
#import "AppDelegate.h"
#import "orderTableViewCell.h"
#import "detailsViewController.h"
#import "list.h"
#define zifu 20
#define Kconfirm @"http://www.51anys.com:8080/waimaiwang/order/getOrder"

@interface evaluationViewController (){
    AppDelegate *app;
    NSString *str;
    NSMutableArray *array;
    NSDictionary *dic;
    NSMutableArray *lbarray;
    NSString *totalCount;
    NSString *index;
}

@property (nonatomic,strong)RefreshControl * refreshControl;

@end

@implementation evaluationViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"zixingche"]]];
        self.navigationItem.title=@"订单列表";
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    str = app._id;
    lbarray = [NSMutableArray array];
    
    //默认跳过条数为0
    index = @"0";
    
    [self loading];
    
    _refreshControl=[[RefreshControl alloc] initWithScrollView:self.tableview delegate:self];
    _refreshControl.topEnabled=NO;
    _refreshControl.bottomEnabled=YES;
    
    [self.tableview reloadData];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction==RefreshDirectionTop)
    {
        
        [lbarray removeAllObjects];
        
    }
    else if (direction==RefreshDirectionBottom)
    {
        
    }
    
    __weak typeof(self)weakSelf=self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf=weakSelf;
        [strongSelf reloadData];
    });
    
}

-(void)reloadData
{
    
    index=[NSString stringWithFormat:@"%d",[index intValue]+10];
    
    [self loading];
    
    if (self.refreshControl.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refreshControl.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionBottom];
        
    }
    
    [self.tableview reloadData];
}

-(void)loading{
    NSURL *url=[NSURL URLWithString:Kconfirm];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"userId=%@&state=%d&index=%d",str,2,[index intValue]];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:array waitUntilDone:YES];
        totalCount = dic[@"totalCount"];
        array = dic[@"orderList"];
        if (totalCount == 0) {
            [self label];
        }else{
            for (NSDictionary *obj in array) {
                list *liebiao1 = [[list alloc]init];
                liebiao1.pic = obj[@"image"];
                liebiao1.name = obj[@"shopName"];
                liebiao1.number = obj[@"orderId"];
                liebiao1.time = obj[@"orderTime"];
                liebiao1.state = obj[@"state"];
                [lbarray addObject:liebiao1];
            }
            [self.tableview reloadData];
        }
    }];
    
}
-(void)refreshData:(NSArray *)sender{
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return lbarray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UINib *nib=[UINib nibWithNibName:@"orderTableViewCell" bundle:nil];
    [_tableview registerNib:nib forCellReuseIdentifier:@"ordercell"];
    static NSString *CellIdentifier = @"ordercell";
    orderTableViewCell *cell = [_tableview dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[orderTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    list *liebiao2 = lbarray[indexPath.row];
    NSString *s = @"http://www.51anys.com:8080/waimaiwang/resources/";
    NSString *string = [NSString stringWithFormat:@"%@",liebiao2.pic];
    NSString *string1 = [NSString stringWithFormat:@"%@%@",s,string];
    NSURL *url = [NSURL URLWithString:string1];
    cell._pic.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    cell.pjdbtp = url;
    cell._name.text =[NSString stringWithFormat:@"%@", liebiao2.name];
    cell.pjdianming = [NSString stringWithFormat:@"%@", liebiao2.name];
    cell._number.text = [NSString stringWithFormat:@"%@",liebiao2.number ];
    cell.pjddid = [NSString stringWithFormat:@"%@",liebiao2.number ];
    //时间戳转换成时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[liebiao2.time doubleValue]/1000];
    NSString *timeSp = [formatter stringFromDate:confromTimesp];
    cell._time.text=timeSp;
    cell._state.text = [NSString stringWithFormat:@"%@",liebiao2.state];
    cell.button1.hidden = NO;
    [cell.button1 setTitle:@"评价" forState:UIControlStateNormal];
    cell.button2.hidden = NO;
    [cell.button2 setTitle:@"配送状态" forState:UIControlStateNormal];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    list *lb = lbarray[indexPath.row];
    static NSString *CellIdentifier = @"ordercell";
    orderTableViewCell *cell = [_tableview dequeueReusableCellWithIdentifier:CellIdentifier];
    cell._number.text = [NSString stringWithFormat:@"%@",lb.number];
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.dingdanid = cell._number.text;
    detailsViewController *details = [self.storyboard instantiateViewControllerWithIdentifier:@"detailsViewC"];
    [self.navigationController pushViewController:details animated:YES];
}
-(void)label{
    UILabel *lab = [[UILabel alloc]init];
    CGFloat labX = 100;
    CGFloat labY = 100;
    CGFloat labW = zifu * 6;
    CGFloat labH = zifu;
    lab.textColor = [UIColor redColor];
    lab.text = @"没有相关订单";
    lab.font = [UIFont systemFontOfSize:20];
    lab.frame = CGRectMake(labX, labY, labW, labH);
    [self.view addSubview:lab];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
